import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2023-02-12
 * Time: 12:09
 */
public class test10 {
    //删除指定文件
    public static void main(String[] args) throws IOException {
        //1.让用户输入必要信息
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入要扫描的路径");
        File rootDir=new File(scanner.next());
        if(!rootDir.isDirectory()){
            System.out.println("输入的目录不存在");
            return;
        }
        System.out.println("请输入要搜索的关键词");
        String toDelete=scanner.next();

        //2.遍历目录，借助核心方法
        //listFiles 能把当前目录里的文件和子目录列出来
         scanDir(rootDir,toDelete);
    }

    private static void scanDir(File rootDir, String toDelete) throws IOException {
        File[] files = rootDir.listFiles();
        if(files==null){
            return;
        }
        for(File file:files){
            System.out.println("当前访问"+file.getCanonicalPath());
            if(!file.isDirectory()){
                scanDir(file,toDelete);
            }else{
                //不是目录，判断文件是否符合要求
                checkDir(file,toDelete);
            }

        }
    }

    private static void checkDir(File file, String toDelete) throws IOException {
        Scanner sc=new Scanner(System.in);
        if(file.getName().contains(toDelete)){
            System.out.println("该单词"+toDelete+" 被 "+file.getCanonicalPath()+"包含了，是否要删除？(Y/N)");
            String s=sc.next();
            if(s.equals("Y")||s.equals("y")){
                file.delete();
                System.out.println("删除成功！");
            }
        }
    }
}
